<?php

class UserController extends BaseController
{
    protected $tableName = "user";
    protected $pk = "user_id";

    private $projectBaseURL = "http://localhost/web-course-backend/";

    public function __construct()
    {
        parent::__construct();
    }

    // GET
    public function get($id)
    {
        $sql = "SELECT u.*, c.name as 'city', i.industry_name as 'industry'
                FROM user u
                LEFT JOIN city c
                ON u.city_id = c.city_id
                LEFT JOIN industry i
                ON	u.industry_id = i.industry_id
                WHERE u.user_id = $id;";
        $result = $this->conn->query($sql);
        $data = $this->getSingleDataFromResult($result);

        if (empty($data)) {
            return ReturnHelper::failed([], "userID不存在", 404);
        }
        else{
            return ReturnHelper::success($data, "数据请求成功");
        }
    }

    public function checkIsFollowed($id, $target)
    {
        $sql = "SELECT count(f.target) AS isFollowed
                FROM user_follow f, (SELECT target FROM user_follow WHERE follower = $id) t1
                WHERE t1.target = f.target AND f.target = $target;";
        $result = $this->conn->query($sql);
        $data = $this->getSingleDataFromResult($result);
        if (empty($data)) {
            return ReturnHelper::failed([], "userID不存在", 404);
        }
        else{
            return ReturnHelper::success($data, "数据请求成功");
        }
    }
    // GET 获取当前用户的所有回答
    public function getAnswer($id)
    {
        $isThumbUp = "IF((
                    SELECT id
                    FROM answer_thumb_up atu
                    WHERE atu.user_id = $id AND answer_id = A.answer_id
                ) IS NULL, FALSE, TRUE) 'is_thumb_up'";
        $isCollect = "IF((
                    SELECT collect_id
                    FROM user_collect uc
                    WHERE uc.user_id = $id AND uc.answer_id = A.answer_id
                ) IS NULL, FALSE, TRUE) 'is_collect'";
        $sql = "SELECT A.*, U.nickname, U.signature,U.avatar_url, $isThumbUp, $isCollect
                FROM answer A, user U WHERE A.user_id = $id And U.user_id = $id";
        $result = $this->conn->query($sql);
        $data = $this->getArrayDataFromResult($result);

        if (empty($data)) {
            return ReturnHelper::failed([], "该用户没有回答任何问题");
        }
        else{
            return ReturnHelper::success($data, "数据请求成功");
        }
    }

    // 获取当前用户的所有收藏的文章
    public function getCollects($id)
    {
        $isThumbUp = "IF((
                    SELECT id
                    FROM answer_thumb_up atu
                    WHERE atu.user_id = $id AND answer_id = a.answer_id
                ) IS NULL, FALSE, TRUE) 'is_thumb_up'";
        $sql = "SELECT a.* ,u.nickname AS answer_user_nickname, u.signature, u.avatar_url, $isThumbUp, true 'is_collect', q.question_title
                FROM answer a, user_collect c, user u, question q
                WHERE a.answer_id = c.answer_id
                AND c.user_id = $id
                AND u.user_id = a.user_id
                AND a.question_id = q.question_id";
        $result = $this->conn->query($sql);
        $data = $this->getArrayDataFromResult($result);

        if (empty($data)) {
            return ReturnHelper::failed([], "该用户没有发表任何评论");
        }
        else{
            return ReturnHelper::success($data, "数据请求成功");
        }
    }

    public function getFollowInfo($id)
    {
        $sql = "SELECT u.nickname, u.signature, COUNT(a.user_id) AS 'answer_num', u.fans_num, u.avatar_url, u.user_id
                FROM user_follow f, user u, answer a
                WHERE follower = $id 
                AND target = u.user_id 
                AND u.user_id = a.user_id 
                GROUP BY a.user_id;";
        $result = $this->conn->query($sql);
        $data = $this->getArrayDataFromResult($result);

        if (empty($data)) {
            return ReturnHelper::failed([], "该用户没有关注任何人", 404);
        }
        else{
            return ReturnHelper::success($data, "数据请求成功");
        }
    }

    //POST 收藏文章接口
    public function collectAnswer($id, $answerId) {
        $sql = "SELECT * FROM user_collect WHERE user_id = $id AND answer_id = $answerId";
        $result = $this->conn->query($sql);
        $data = $this->getSingleDataFromResult($result);
        if (!empty($data)) {
            return ReturnHelper::failed([], "用户`$id`已经收藏过回答`$answerId`");
        }
        else {
            $ucController = new UserCollectController();
            $data = $ucController->post([
                "user_id" => $id,
                "answer_id" => $answerId
            ]);
            if ($data['state']===200) {
                $ansController = new AnswerController();
                return ReturnHelper::success($ansController->get($answerId)['data'], "用户`$id`收藏回答`$answerId`成功");
            }
            else {
                return ReturnHelper::success([], "UserCollectController::post出现问题");
            }
        }
    }

    // DELETE 取消收藏接口
    public function disCollectAnswer($id, $answerId) {
        $sql = "SELECT * FROM user_collect WHERE user_id = $id AND answer_id = $answerId";
        $result = $this->conn->query($sql);
        $data = $this->getSingleDataFromResult($result);
        if (empty($data)) {
            return ReturnHelper::failed([], "用户`$id`没有收藏回答`$answerId`，无法取消收藏");
        }
        else {
            $ucController = new UserCollectController();
            $data = $ucController->delete($data['collect_id']);
            if ($data['state']===200) {
                $ansController = new AnswerController();
                return ReturnHelper::success($ansController->get($answerId)['data'], "用户`$id`取消收藏回答`$answerId`成功");
            }
            else {
                return ReturnHelper::success([], "UserCollectController::post出现问题");
            }
        }
    }

    //POST 新建评论接口
    public function newComment($id, $obj) {
        $answer_id = $obj["answer_id"];
        $comment_content = $obj['comment_content'];
        $commentController = new CommentController();
        $data = $commentController->post([
            "user_id" => $id,
            "answer_id" => $answer_id,
            "comment_content" => $comment_content
        ]);
        if ($data['state'] === 200) {
            return ReturnHelper::success($data['data'], "用户`$id`在问题`$answer_id`下新建评论成功");
        }
        else {
            return ReturnHelper::failed([], "用户`$id`在问题`$answer_id`下新建评论失败");
        }
    }

    //POST 新建回复信息接口
    public function newReply($from_id, $to_id, $obj) {
        $comment_id = $obj['comment_id'];
        $content = $obj['content'];
        $cpController = new CommentReplyController();
        $data = $cpController->post([
            "comment_id" => $comment_id,
            "user_from" => $from_id,
            "user_to" => $to_id,
            "cm_reply_content" => $content
        ]);
        if ($data['state'] === 200) {
            return ReturnHelper::success($data['data'], "在评论`$comment_id`下用户`$from_id`给用户`$to_id`回复成功");
        }
        else {
            return ReturnHelper::failed([], "在评论`$comment_id`下用户`$from_id`给用户`$to_id`回复失败");
        }
    }

    //POST 给某回答点赞
    public function thumbUpAnswer($user_id, $answer_id) {
        $ATUPController = new AnswerThumbUpController();
        // 如果已经点过赞则返回失败信息
        if ($ATUPController->hasThumbUpRecord($user_id, $answer_id)) {
            return ReturnHelper::failed([], "用户`$user_id`已经为回答`$answer_id`点过赞了");
        }
        $newThumbUp = $ATUPController->post([
            "user_id" => $user_id,
            "answer_id" => $answer_id
        ]);
        if ($newThumbUp['state'] !== 200) {
            return ReturnHelper::failed([],"点赞失败");
        }
        else {
            $answerController = new AnswerController();
            $data = $answerController->get($answer_id);
            $data['data']['is_thumb_up'] = "1";
            return ReturnHelper::success($data['data'], "`$user_id`给answer：`$answer_id`点赞成功！");
        }
    }

    // DELETE 取消点赞
    public function unThumbUpAnswer($user_id, $answer_id) {
        $ATUPController = new AnswerThumbUpController();
        $data = $ATUPController->hasThumbUpRecord($user_id, $answer_id);
        if ($data === false) {
            return ReturnHelper::failed([], "用户`$user_id`还没有为回答`$answer_id`点赞，无法取消点赞");
        }
        $data = $ATUPController->delete($data['id']);
        if ($data['state'] === 200) {
            $answerController = new AnswerController();
            $data = $answerController->get($answer_id);
            $data['data']['is_thumb_up'] = "0";
            return ReturnHelper::success($data['data'], "用户`$user_id`给回答`$answer_id`取消点赞成功");
        }
        else {
            return ReturnHelper::success($data['data'], "AnswerThumbUpController::delete失败，取消点赞失败");
        }
    }

    //POST 关注其他用户
    public function followUser($id, $target) {
        $ufController = new UserFollowController();
        $data = $ufController->post([
            "follower" => $id,
            "target" => $target
        ]);
        if ($data['state'] === 200) {
            return ReturnHelper::success($data['data'], "用户`$id`关注`$target`成功");
        }
        else {
            return ReturnHelper::failed([], "用户`$id`关注`$target`失败：".$data['msg']);
        }
    }

    // DELETE 取消关注其他用户
    public function unFollowUser($id, $target) {
        // 查询数据库中是否有用户id关注target的记录
        $sql = "SELECT * FROM user_follow WHERE follower=$id AND target=$target";
        $result = $this->conn->query($sql);
        $data = $this->getSingleDataFromResult($result);
        if (empty($data)) {
            // 如果记录不存在代表没有进行关注
            return ReturnHelper::failed([], "用户`$id`没有关注用户`$target`，无法取消关注");
        }
        else {
            $ufController = new UserFollowController();
            $deleteRes = $ufController->delete($data['follow_id']);
            if ($deleteRes['state']===200) {
                return ReturnHelper::success([], "用户`$id`解除对用户`$target`的关注成功");
            }
            else {
                return ReturnHelper::failed([], "UserFollowController::delete解除关注失败");
            }
        }
    }

    // PUT 修改用户信息
    public function update($id, $obj)
    {
        $user_id = $obj['user_id'];
        $getRes = $this->get($id)['data'];
        if ($getRes['user_id'] != $user_id){
            return ReturnHelper::failed([],"不可修改他人信息");
        }
        return parent::update($id, $obj);
    }

    // POST 修改头像
    public function uploadPhoto($id){

        if($_FILES["file"]["error"] > 0){
            return ReturnHelper::failed([],"文件过大");
        }
        else{
            $array = $_FILES["file"]["type"];
            $array = explode("/",$array);
            $newfilename = $this->uuid();
            $_FILES["file"]["name"] = $newfilename.".".$array[1];
            if (!is_dir("photo/". $id)){
                mkdir("photo/". $id);
            }
            $avatar_url = "photo/". $id . "/";
            $avatar_url=$avatar_url.$_FILES["file"]["name"];
            move_uploaded_file($_FILES["file"]["tmp_name"],$avatar_url);
            $obj = [
                "avatar_url"=>$this->projectBaseURL . $avatar_url
            ];
            parent::update($id, $obj);
            return ReturnHelper::success(["user_id"=>$id,"avatar_url"=>$this->projectBaseURL . $avatar_url], "图片上传至上述url");
        }
    }

    public function uuid()
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr ( $chars, 0, 8 ) . '-'
            . substr ( $chars, 8, 4 ) . '-'
            . substr ( $chars, 12, 4 ) . '-'
            . substr ( $chars, 16, 4 ) . '-'
            . substr ( $chars, 20, 12 );
        return $uuid ;
    }
}